<template>
  <div style="padding: 0 2px">
    <template v-if="auth === 'edit'">
      <a-input-number
        :step="step"
        style="width: 100%" :min="min" :max="max"
        @blur="blur" @focus="focus" v-model="innerValue"
        :placeholder="fieldConfig.placeholder"/>
    </template>
    <template v-else>
      <span style="white-space: pre-wrap" v-html="innerValueString"/>
    </template>
  </div>
</template>
<script>
import {createProps} from '@/utils';

export default {
  name: 'NumberField',
  props: {
    fieldConfig: createProps(Object),
    value: {
      type: [Number, String],
      default: undefined
    },
    title: {
      type: [Number, String],
      default: undefined
    },
    auth: createProps(String)
  },
  methods: {
    blur() {
      (this.tempValue !== this.value) && this.$emit('update');
    },
    focus() {
      this.tempValue = this.value;
    }
  },
  computed: {
    min() {
      try {
        return parseFloat(this.fieldConfig.minValue);
      } catch (e) {
      }
      return Infinity;
    },
    max() {
      try {
        return parseFloat(this.fieldConfig.maxValue);
      } catch (e) {
      }
      return Infinity;
    },
    step() {
      try {
        let i = this.fieldConfig.length, res = 1;
        if (i > 5) i = 5;
        if (i < 0) i = 0;
        while (i--) res /= 10;
        return res;
      } catch (e) {
      }
      return 0;
    },
    innerValueString() {
      if(this.innerValue === null || this.innerValue === undefined) return ''
      try {
        return parseFloat(this.innerValue + '').toFixed(this.fieldConfig.length) + '';
      } catch (e) {}
      return ''
    },
    innerValue: {
      get() {
        if(this.value === null || this.value === undefined) return undefined
        let res = this.value || this.title;
        try {
          if(res == 0 || this.value == 0) return 0
          return parseFloat(res && (res + '')) || undefined;
        } catch (e) {}
        return undefined
      },
      set(v) {
        this.$emit('update:value', v);
        this.$emit('update:title', v);
      },
    }
  }
};
</script>